// src/router/index.js
import { createRouter, createWebHistory } from 'vue-router'
import Home from '@/views/Home.vue'
import ProductSearch from '@/views/ProductSearch.vue'
import Admin from '@/views/Admin.vue'
import LoginPage from '@/views/LoginPage.vue'
import { setupAuthGuard, setupTitleGuard } from '@/router/auth_guard'

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/search',
    name: 'ProductSearch',
    component: ProductSearch
  },
  {
    path: '/login',
    name: 'Login',
    component: LoginPage,
    meta: {
      title: '登录',
      requiresAuth: false
    }
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('@/views/Register.vue')
  },
  {
    path: '/admin',
    name: 'Admin',
    component: Admin,
    meta: { requiresAuth: true, requiresRole: 'admin' }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// // src/router/index.js 继续
// router.beforeEach((to, from, next) => {
//   const isLoggedIn = !!localStorage.getItem('token') // 👈 假设登录后存了 token

//   if (to.meta.requiresAuth && !isLoggedIn) {
//     next('/login') // 未登录，跳转登录页
//   } else {
//     next() // 已登录，正常跳转
//   }
// })

// 设置路由守卫
setupAuthGuard(router)
setupTitleGuard(router)

// 导出路由实例
export default router
